import type { ComponentInfo, ComponentProp, ComponentExample } from '../types/index.js';

export class ComponentRegistry {
  private components: Map<string, ComponentInfo> = new Map();
  private componentCache: Map<string, ComponentInfo[]> = new Map();
  private searchCache: Map<string, ComponentInfo[]> = new Map();
  private initialized = false;

  constructor() {
    this.initializeComponents();
  }

  private initializeComponents(): void {
    if (this.initialized) return;
    
    // 批量初始化基础组件（最常用的）
    this.batchRegisterBasicComponents();
    
    this.initialized = true;
  }

  private batchRegisterBasicComponents(): void {
    // Ant Design 基础组件
    this.registerComponent({
      name: 'Button',
      category: 'basic',
      description: '按钮用于开始一个即时操作',
      props: [
        {
          name: 'type',
          type: 'primary | default | dashed | link | text',
          required: false,
          description: '设置按钮类型',
          defaultValue: 'default',
          options: ['primary', 'default', 'dashed', 'link', 'text']
        },
        {
          name: 'size',
          type: 'large | middle | small',
          required: false,
          description: '设置按钮大小',
          defaultValue: 'middle',
          options: ['large', 'middle', 'small']
        },
        {
          name: 'disabled',
          type: 'boolean',
          required: false,
          description: '按钮失效状态',
          defaultValue: false
        },
        {
          name: 'loading',
          type: 'boolean',
          required: false,
          description: '设置按钮载入状态',
          defaultValue: false
        },
        {
          name: 'onClick',
          type: '(event: MouseEvent) => void',
          required: false,
          description: '点击按钮时的回调'
        }
      ],
      examples: [
        {
          title: '基础按钮',
          description: '基本的按钮用法',
          code: `<Button type="primary">Primary Button</Button>
<Button>Default Button</Button>
<Button type="dashed">Dashed Button</Button>
<Button type="text">Text Button</Button>
<Button type="link">Link Button</Button>`
        },
        {
          title: '按钮尺寸',
          description: '按钮有大、中、小三种尺寸',
          code: `<Button type="primary" size="large">Large</Button>
<Button type="primary" size="middle">Middle</Button>
<Button type="primary" size="small">Small</Button>`
        }
      ],
      imports: ['import { Button } from "antd";']
    });

    this.registerComponent({
      name: 'Table',
      category: 'data-display',
      description: '展示行列数据',
      props: [
        {
          name: 'dataSource',
          type: 'any[]',
          required: true,
          description: '数据数组'
        },
        {
          name: 'columns',
          type: 'ColumnsType<T>',
          required: true,
          description: '表格列的配置'
        },
        {
          name: 'loading',
          type: 'boolean | SpinProps',
          required: false,
          description: '页面是否加载中',
          defaultValue: false
        },
        {
          name: 'pagination',
          type: 'false | TablePaginationConfig',
          required: false,
          description: '分页器配置'
        },
        {
          name: 'rowKey',
          type: 'string | (record: T) => string',
          required: false,
          description: '表格行 key 的取值',
          defaultValue: 'key'
        }
      ],
      examples: [
        {
          title: '基础表格',
          description: '简单的表格，最后一列是各种操作',
          code: `const columns = [
  {
    title: '姓名',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '年龄',
    dataIndex: 'age',
    key: 'age',
  },
  {
    title: '住址',
    dataIndex: 'address',
    key: 'address',
  },
];

const dataSource = [
  {
    key: '1',
    name: '胡彦斌',
    age: 32,
    address: '西湖区湖底公园1号',
  },
  {
    key: '2',
    name: '胡彦祖',
    age: 42,
    address: '西湖区湖底公园1号',
  },
];

<Table dataSource={dataSource} columns={columns} />`
        }
      ],
      imports: ['import { Table } from "antd";', 'import type { ColumnsType } from "antd/es/table";']
    });

    this.registerComponent({
      name: 'Form',
      category: 'data-entry',
      description: '高性能订阅式表单，一套绝佳的数据域管理流程',
      props: [
        {
          name: 'form',
          type: 'FormInstance',
          required: false,
          description: '经 Form.useForm() 创建的 form 控制实例'
        },
        {
          name: 'layout',
          type: 'horizontal | vertical | inline',
          required: false,
          description: '表单布局',
          defaultValue: 'horizontal',
          options: ['horizontal', 'vertical', 'inline']
        },
        {
          name: 'onFinish',
          type: '(values: any) => void',
          required: false,
          description: '提交表单且数据验证成功后回调事件'
        },
        {
          name: 'onFinishFailed',
          type: '(errorInfo: ValidateErrorEntity) => void',
          required: false,
          description: '提交表单且数据验证失败后回调事件'
        }
      ],
      examples: [
        {
          title: '基础表单',
          description: '基本的表单数据域控制展示，包含布局、初始化、验证、提交',
          code: `const onFinish = (values: any) => {
  console.log('Success:', values);
};

const onFinishFailed = (errorInfo: any) => {
  console.log('Failed:', errorInfo);
};

<Form
  name="basic"
  labelCol={{ span: 8 }}
  wrapperCol={{ span: 16 }}
  style={{ maxWidth: 600 }}
  initialValues={{ remember: true }}
  onFinish={onFinish}
  onFinishFailed={onFinishFailed}
  autoComplete="off"
>
  <Form.Item
    label="Username"
    name="username"
    rules={[{ required: true, message: 'Please input your username!' }]}
  >
    <Input />
  </Form.Item>

  <Form.Item
    label="Password"
    name="password"
    rules={[{ required: true, message: 'Please input your password!' }]}
  >
    <Input.Password />
  </Form.Item>

  <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
    <Button type="primary" htmlType="submit">
      Submit
    </Button>
  </Form.Item>
</Form>`
        }
      ],
      imports: ['import { Form, Input, Button } from "antd";']
    });

    // Pro Components
    this.registerComponent({
      name: 'ProTable',
      category: 'pro',
      description: '高级表格，集成了查询表单，具有查询，刷新等好用的功能',
      props: [
        {
          name: 'columns',
          type: 'ProColumns<T>[]',
          required: true,
          description: '表格列配置，支持搜索等配置'
        },
        {
          name: 'request',
          type: '(params: any) => Promise<{data: T[], success: boolean, total: number}>',
          required: false,
          description: '获取数据的方法'
        },
        {
          name: 'toolBarRender',
          type: '() => React.ReactNode[]',
          required: false,
          description: '工具栏渲染'
        },
        {
          name: 'search',
          type: 'false | SearchConfig',
          required: false,
          description: '是否显示搜索表单'
        }
      ],
      examples: [
        {
          title: '基础 ProTable',
          description: '具有查询功能的高级表格',
          code: `import { ProTable } from '@ant-design/pro-components';

const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    valueType: 'indexBorder',
    width: 48,
  },
  {
    title: '标题',
    dataIndex: 'title',
    copyable: true,
    ellipsis: true,
    tooltip: '标题过长会自动收缩',
    formItemProps: {
      rules: [
        {
          required: true,
          message: '此项为必填项',
        },
      ],
    },
  },
  {
    title: '状态',
    dataIndex: 'state',
    filters: true,
    onFilter: true,
    valueType: 'select',
    valueEnum: {
      all: { text: '超长'.repeat(50) },
      open: {
        text: '未解决',
        status: 'Error',
      },
      closed: {
        text: '已解决',
        status: 'Success',
        disabled: true,
      },
      processing: {
        text: '解决中',
        status: 'Processing',
      },
    },
  },
];

<ProTable
  columns={columns}
  request={async (params) => {
    // 模拟请求
    return {
      data: [],
      success: true,
      total: 0,
    };
  }}
  rowKey="id"
  search={{
    labelWidth: 'auto',
  }}
  pagination={{
    pageSize: 5,
    onChange: (page) => console.log(page),
  }}
  dateFormatter="string"
  headerTitle="高级表格"
  toolBarRender={() => [
    <Button key="button" icon={<PlusOutlined />} type="primary">
      新建
    </Button>,
  ]}
/>`
        }
      ],
      imports: ['import { ProTable } from "@ant-design/pro-components";'],
      dependencies: ['@ant-design/pro-components']
    });

    // Ant Design Charts
    this.registerComponent({
      name: 'Line',
      category: 'charts',
      description: '折线图，用于展示数据在连续时间间隔或有序类别间的变化趋势',
      props: [
        {
          name: 'data',
          type: 'any[]',
          required: true,
          description: '设置图表数据源'
        },
        {
          name: 'xField',
          type: 'string',
          required: true,
          description: 'x 轴字段名'
        },
        {
          name: 'yField',
          type: 'string',
          required: true,
          description: 'y 轴字段名'
        },
        {
          name: 'seriesField',
          type: 'string',
          required: false,
          description: '分组字段名'
        }
      ],
      examples: [
        {
          title: '基础折线图',
          description: '最简单的折线图',
          code: `import { Line } from '@ant-design/charts';

const data = [
  { year: '1991', value: 3 },
  { year: '1992', value: 4 },
  { year: '1993', value: 3.5 },
  { year: '1994', value: 5 },
  { year: '1995', value: 4.9 },
  { year: '1996', value: 6 },
  { year: '1997', value: 7 },
  { year: '1998', value: 9 },
  { year: '1999', value: 13 },
];

<Line
  data={data}
  xField="year"
  yField="value"
  point={{
    size: 5,
    shape: 'diamond',
  }}
/>`
        }
      ],
      imports: ['import { Line } from "@ant-design/charts";'],
      dependencies: ['@ant-design/charts']
    });
  }

  registerComponent(component: ComponentInfo): void {
    this.components.set(component.name, component);
  }

  getComponent(name: string): ComponentInfo | undefined {
    return this.components.get(name);
  }

  getAllComponents(): ComponentInfo[] {
    return Array.from(this.components.values());
  }

  searchComponents(query: string, category?: string, limit = 10): ComponentInfo[] {
    const components = Array.from(this.components.values());
    
    let filtered = components.filter(comp => {
      const matchesQuery = comp.name.toLowerCase().includes(query.toLowerCase()) ||
                          comp.description.toLowerCase().includes(query.toLowerCase());
      const matchesCategory = !category || comp.category === category;
      return matchesQuery && matchesCategory;
    });

    return filtered.slice(0, limit);
  }

  getComponentsByCategory(category: string): ComponentInfo[] {
    return Array.from(this.components.values()).filter(comp => comp.category === category);
  }
}